<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class AuthController extends BaseController
{
    public function login(Request $request)
    {
        $input = $request->input();
        if (!empty($input['user_id'])) {
            $user = User::find($input['user_id']);
            if (!$token = \Auth::guard('api')->fromUser($user)) {
                return $this->failed('登录失败', 401);
            }
            return $this->respondWithToken($token);
        }
        \Log::info("weixin-login-param : " . var_export($input, true));
        $this->validate($request, [
            'code' => 'required',
            'encryptedData' => 'required',
            'iv' => 'required',
        ]);
        $app = $this->miniProgram();

        $session = $app->auth->session($request->code);
        \Log::info("weixin-session : " . var_export($session, true));
        if (isset($session['errcode']) &&  $session['errcode'] > 0)
            return $this->failed($session['errmsg']);

        try {
            $userInfo = $app->encryptor->decryptData(
                $session['session_key'],
                $request->iv,
                $request->encryptedData
            );
            \Log::info("weixin-decrypt : " . var_export($userInfo, true));
        } catch (\Exception $e) {
            \Log::error($e->getMessage());
            return $this->failed('网络异常，请重新操作');
        }

        $cache_key = 'login_open_id' . $session['openid'];
        if (Redis::setnx($cache_key, 1)) {
            Redis::expire($cache_key, 10);
            try {
                $user = User::where('weixin_openid', $session['openid'])->first();
                if (!$user) {
                    $user = new User();
                    $user->weixin_openid = $session['openid'];
                    $user->session_key = $session['session_key'];
                    $user->nickname = $userInfo['nickName'];
                    $user->gender = $userInfo['gender'];
                    $user->avatar_url = $userInfo['avatarUrl'];
                    $user->save();
                } else {
                    $user->session_key = $session['session_key'];
                    $user->save();
                }
                $cache_key = $user->getMorphClass() . ":" . $user->id;
                \Cache::forget($cache_key);

                if (!$token = \Auth::guard('api')->fromUser($user)) {
                    return $this->failed('登录失败', 401);
                }

                return $this->respondWithToken($token);
            } catch (\Exception $e) {
                \Log::error($e);
                Redis::del($cache_key);
                return $this->failed($e->getMessage());
            }
        } else {
            return $this->failed("登录失败，请重试");
        }
    }




}